package services.image;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Iterator;
import play.libs.WS;
import play.libs.WS.HttpResponse;
import services.image.ImageSearchService.ImageExt;
import play.Logger;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import controllers.Data;

public class GoogleSearchServiceImpl implements ImageSearchService {
	
	private static final String searchPattern = "https://www.googleapis.com/customsearch/v1?key=AIzaSyCL0UgC81niErOsBxkWIfb41x1K9hYMsyU&cx=011359263304779554140:qfjrq8katyw&q=%s&start=%s&num=%s&fields=queries/nextPage/totalResults,items(title,pagemap/cse_image,pagemap/cse_thumbnail)";
	
	@Override
	public Data<ImageExt> search(String terms, int offset, int limit) throws IOException {
		if(limit>10) limit=10;
		Data<ImageExt> images = new Data<ImageExt>();
		images.total = 0;
		images.data = new ArrayList<ImageExt>();
		HttpResponse response = WS.url(searchPattern, terms, ""+offset, ""+limit).get();
		 if( response.getStatus() == 200 ) {
			Reader reader = new InputStreamReader(response.getStream());
			JsonObject jsobj = new JsonParser().parse(reader).getAsJsonObject();
			int totalResults = jsobj.get("queries").getAsJsonObject().get("nextPage").getAsJsonArray().iterator().next().getAsJsonObject().get("totalResults").getAsInt();	
			images.total = totalResults;
			Iterator<JsonElement> itemsIt = jsobj.get("items").getAsJsonArray().iterator();
			while(itemsIt.hasNext()) {
				JsonObject item = itemsIt.next().getAsJsonObject();
				ImageExt image = new ImageExt();
				image.title = item.get("title").getAsString();
				Logger.info("Pagemap %s ", item.get("pagemap"));
				if(item.get("pagemap")!=null) {
					if(item.get("cse_image")!=null) {
						JsonObject cse_image = item.get("cse_image").getAsJsonArray().iterator().next().getAsJsonObject();
						image.original = cse_image.get("src").getAsString();
					}
					if(item.get("cse_thumbnail")!=null) {
						JsonObject cse_thumbnail = item.get("cse_thumbnail").getAsJsonArray().iterator().next().getAsJsonObject();
						image.original = cse_thumbnail.get("src").getAsString();
					}
				}
				images.data.add(image);
				
			}
		 }
		 return images;
	}

}
